package com.seeyon.apps.kkARPEvent.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.log.CtpLogFactory;
import org.apache.commons.logging.Log;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

public class KKTokensUtil {

    private static final Log log = CtpLogFactory.getLog(KKTokensUtil.class);

    private static final String URL = AppContext.getSystemProperty("ARPUrl.IP");
    private static final String TOKEN_URL = AppContext.getSystemProperty("ARPtoken.TokenUrl"); //API URL
    private static final String APP_KEY = AppContext.getSystemProperty("ARPtoken.AppKey"); // appKey
    private static final String APP_PASSWORD = AppContext.getSystemProperty("ARPtoken.AppPassword"); // appPassword

    /**
     * 获取AccessToken
     * @return
     */
    public static String getAccessToken() {
        log.info("客开日志-----------【getAccessToken】start");
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost post = new HttpPost(URL +TOKEN_URL);
            post.setHeader("Content-Type", "application/json");

            // 构建请求体
            Map<String, String> requestBody = new HashMap<>();
            requestBody.put("appKey", APP_KEY);
            requestBody.put("appPassword", APP_PASSWORD);
            String jsonRequestBody = JSON.toJSONString(requestBody);

            // 设置请求体
            post.setEntity(new StringEntity(jsonRequestBody, "UTF-8"));
            log.info("客开日志-----------【getAccessToken】发送的请求体: " + jsonRequestBody);

            // 发送请求并解析响应
            try (CloseableHttpResponse response = httpClient.execute(post)) {
                log.info("客开日志-----------【getAccessToken】响应状态码: " + response.getStatusLine().getStatusCode());
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String responseString = EntityUtils.toString(entity, "UTF-8");
                    log.info("客开日志-----------【getAccessToken】获取Token的响应: " + responseString);

                    // 解析响应
                    JSONObject jsonResponse = JSON.parseObject(responseString);
                    if (jsonResponse.containsKey("access")) { // 检查是否存在 "access" 字段
                        JSONObject accessTokenObject = jsonResponse.getJSONObject("access");
                        String token = accessTokenObject.getString("token");
                        log.info("客开日志-----------【getAccessToken】AccessToken==> " + token);
                        return token;
                    } else {
                        log.error("客开日志-----------【getAccessToken】获取Token失败: " + responseString);
                    }
                }
            }
        } catch (Exception e) {
            log.error("客开日志-----------【getAccessToken】获取AccessToken失败", e);
        }
        log.info("客开日志-----------【getAccessToken】end");
        return null;
    }


    /**
     * 刷新AccessToken
     * @param refreshToken 刷新用的Token
     * @return 新的AccessToken
     */
    public static String refreshAccessToken(String refreshToken) {
        log.info("客开日志-----------【refreshAccessToken】start");

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 构建URL，替换为实际的代码和 refreshToken
            String refreshUrl = URL +TOKEN_URL + refreshToken;
            HttpPut put = new HttpPut(refreshUrl);
            put.setHeader("Content-Type", "application/json");

            // 不需要请求体，直接发送请求
            log.info("客开日志-----------【refreshAccessToken】发送请求至: " + refreshUrl);

            // 发送请求并解析响应
            try (CloseableHttpResponse response = httpClient.execute(put)) {
                log.info("客开日志-----------【refreshAccessToken】响应状态码: " + response.getStatusLine().getStatusCode());
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String responseString = EntityUtils.toString(entity, "UTF-8");
                    log.info("客开日志-----------【refreshAccessToken】获取Token的响应: " + responseString);

                    // 解析响应
                    JSONObject jsonResponse = JSON.parseObject(responseString);
                    if (jsonResponse.containsKey("access")) { // 检查是否存在 "access" 字段
                        JSONObject accessTokenObject = jsonResponse.getJSONObject("access");
                        String newToken = accessTokenObject.getString("token");
                        log.info("客开日志-----------【refreshAccessToken】新的AccessToken==> " + newToken);
                        return newToken;
                    } else {
                        log.error("客开日志-----------【refreshAccessToken】刷新Token失败: " + responseString);
                    }
                }
            }
        } catch (Exception e) {
            log.error("客开日志-----------【refreshAccessToken】刷新AccessToken失败", e);
        }

        log.info("客开日志-----------【refreshAccessToken】end");
        return null;
    }

}
